import router from "./index";
import store from "/@/store/index";
import { getStorage } from "/@/utils/auth";
import getPageTitle from "/@/utils/get-page-title";

const whiteList = ["/login"]; // 白名单

router.beforeEach(async (to, from, next) => {
  document.title = getPageTitle(to.meta.title as string);
  const hasToken = getStorage("Token");
  if (hasToken) {
    if (to.path === "/login") {
      // if is logged in, redirect to the home page
      next({ path: "/" });
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      if (hasRoles) {
        next();
      } else {
        try {
          const { roles } = await store.dispatch("user/getInfo");
          // 根据用户角色，动态获取有权限的路由
          const accessRoutes = await store.dispatch(
            "permission/generateRoutes",
            roles
          );
          console.log(
            accessRoutes,
            "accessedRoutesaccessedRoutesaccessedRoutesaccessedRoutes"
          );

          // 动态挂载路由
          accessRoutes.forEach((route: any) => {
            // !在vue-router 4.x中，router.addRoutes已经废弃
            router.addRoute(route);
          });
          next({ ...to });
        } catch (error) {
          await store.dispatch("user/regetStorage");
          next(`/login?redirect=${to.path}`);
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});
